/**
 * Created by admin on 2016/8/9.
 */
var assert = require('../assert');
var co = require('co');

exports.getProducts = function (req, res) {
    var productTypeId = req.query.productTypeId;
    var orderBy = req.query.orderBy;
    switch (orderBy){
        case 0:
            orderBy = 'saleCount';
            break;
        case 1:
            orderBy = 'saleCount';
            break;
        case 2:
            orderBy = 'price';
            break;
        default:
            orderBy = 'saleCount';
    }
    // 判断ProductId是否为空
    if (!productTypeId){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    // 分页的初始化参数
    var page = 1;
    var limit = 10;
    // 判断page是否合法
    if (req.query.page){
        try {
            page = parseInt(req.query.page);
        }catch (error){
            page = 1;
        }
    }
    var skip = (page-1) * limit;
    // 实例化商品类
    var ProductType = Parse.Object.extend('OPProductType');
    var productType = new ProductType();
    productType.id = productTypeId;
    // 执行查询
    var query = new Parse.Query('OPProduct');
    query.equalTo('type',productType);
    query.skip(skip);
    query.limit(limit);
    query.select('images', 'price', 'country', 'title', 'salePrice');
    query.descending(orderBy);
    query.find().then(function (results) {
        if (results.length<1){
            res.send(assert.response_sms(200,'没有更多商品了', results))
        }else {
            res.send(assert.response_sms(200,'获取商品列表成功', results))
        }
    }, function (error) {
        res.send(assert.response_sms(400, '获取商品列表失败' + error.message));
    });
};
// 获取单个商品详情
exports.getProduct = function (req, res) {
    var productId = req.params.productId;
    var userId = req.query.userId;
    var isUserExist = typeof userId != 'undefined' && userId != '';
    var isShort = req.query.isshort;
    if (!productId){
        res.send(assert.response_sms(400, 'productId为空'));
        return
    }
    // 创建一个user用来查询优惠券领取情况
    if (isUserExist){
        var user = new Parse.User();
        user.id = userId;
    }
    // 查询商品详情
    var query = new Parse.Query('OPProduct');
    if(isShort){
        query.select('images','title','price','salePrice');
        query.get(productId).then(function (results) {
            var responseContent = assert.obj2dic(results,['title','price','salePrice']);
            responseContent['images'] = results.get('images')[0];
            res.send(assert.response_sms(200, '获取商品成功', responseContent));
        }, function (error) {
            res.send(assert.response_sms(400, '获取商品失败'));
        });
    }else {
        // 查询所有couponTemplate
        var queryTemplateCoupon = new Parse.Query('PYCouponTemplate');
        queryTemplateCoupon.equalTo('from', 'seagou');
        // 查询user已经领取的优惠券
        var queryCoupon = new Parse.Query('PYCoupon');
        queryCoupon.equalTo('user', user);
        var waitFor = [queryTemplateCoupon.find(), query.get(productId)];
        if (isUserExist){
            waitFor.push(queryCoupon.find());
        }
        Promise.all(waitFor).then(function (results) {
            var templateCoupons = results[0];
            var product = results[1];
            if (isUserExist){
                var coupons = results[2];
            }
            var templateCouponList = [];
            if (isUserExist){
                var coupon_list = [];
                coupons.forEach(function (item) {
                    coupon_list.push(item.get('couponTemplate').id)
                });
            }
            // 格式化返回内容
            templateCoupons.forEach(function (item) {
                var temp = assert.obj2dic(item, ['channel', 'worth', 'limitPrice']);
                var now = new Date();
                if (item.get('validityEnd')>now && item.get('validityBegin')<now){
                    temp['isGet'] = false;
                    temp['validityEnd'] = item.get('validityEnd').Format('yyyy-MM-dd');
                    temp['validityBegin'] = item.get('validityBegin').Format('yyyy-MM-dd');
                    if (isUserExist){
                        temp['isGet'] = contains(coupon_list, item.id);
                    }
                    templateCouponList.push(temp);
                }
            });
            var response = assert.obj2dic(product, ['images', 'price', 'title', 'country', 'saleCount', 'info', 'onSale', 'salePrice', 'detailImages', 'imageInfo']);
            response['coupons'] =templateCouponList;
            res.json({'code': 200, 'message': '获取商品成功', 'results': response});
        }, function (error) {
            res.send(assert.response_sms(400, '获取商品详情失败'  + error.message));
        });
    }
};
// 获取商品列表
exports.getProductType = function (req, res) {
    var query = new Parse.Query('OPProductType');
    query.find().then(function (results) {
        var response_content = [];
        for (var i=0; i<results.length; i++){
            response_content.push(assert.obj2dic(results[i], ['title']));
        }
        res.send(assert.response_sms(200, '获取商品类别成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '获取商品类别失败' + error.message));
    })
};
// 获取新品推荐
exports.getNewProducts = function (req, res) {
    var page = req.query.curPage;
    try {
    page = parseInt(page);
    }catch (error){
        page = 1
    }
    // 设定控制值
    var limit = 10;
    var skip = (page-1) * limit;
    var query = new Parse.Query('OPProduct');
    query.skip(skip);
    query.limit(limit);
    query.select('images', 'price', 'country', 'title', 'salePrice');
    query.descending('createAt');
    // 查询
    query.find().then(function (results) {
        if (results.length<1){
            res.send(assert.response_sms(200, '没有更多新品了'));
            return;
        }
        var response_content = [];
        for (var i=0; i<results.length; i++){
            var temp = assert.obj2dic(results[i], ['images', 'price', 'country', 'title', 'salePrice']);
            temp['images'] = temp['images'][0];
            response_content.push(temp);
        }
        res.send(assert.response_sms(200, '获取新品推荐成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '获取新品推荐失败' + error.message));
    });
};
// 搜索商品
exports.getSearchProduct = function (req, res) {
    var keyWord = req.query.keyword;
    var page = req.query.curPage;
    try {
        page = parseInt(page);
    }catch (error){
        page = 1
    }
    // 设定控制值
    var limit = 10;
    var skip = (page-1) * limit;
    keyWord = decodeURI(keyWord);
    var query = new Parse.Query('OPProduct');
    query.contains('title', keyWord);
    query.skip(skip);
    query.limit(limit);
    query.find().then(function (results) {
        if (results.length<1 && page==1){
            res.send(assert.response_sms(200, '没有搜索到商品', results));
        }else if(results.length<1){
            res.send(assert.response_sms(200, '没有更多搜索商品了', results));
        }else {
            var response_content = [];
            for (var i=0; i<results.length; i++){
                var temp = assert.obj2dic(results[i], ['images', 'price', 'country', 'title', 'salePrice']);
                temp['images'] = temp['images'][0];
                response_content.push(temp);
            }
            res.send(assert.response_sms(200, '搜索商品成功', response_content));
        }
    }, function (error) {
       res.send(assert.response_sms(400, '搜索商品失败'))
    });
};

// 获取首页的banner
exports.getBanner = function (req, res) {
    var query = new Parse.Query('OPBanner');
    query.find().then(function (banners) {
        if(banners.length){
            res.send(assert.response_sms(200, '获取banner成功', banners));
        }else{
            res.send(assert.response_sms(200, '获取banner成功', ['/public/images/banner.png']));
        }

    }, function (error) {
        res.send(assert.response_sms(200, '获取banner成功', ['/public/images/banner.png']));
    });
};

// 领取优惠券接口
exports.postCoupon = function (req, res) {
    var userId = req.body.userId;
    var couponTemplateId = req.body.couponId;
    if (assert.check_parms([userId, couponTemplateId])){
        res.json({'code':101, 'message': 'userId, templateCouponId参数不能为空'});
    }
    // 创建指定的couponTemplate
    var CouponTemplate = Parse.Object.extend('PYCouponTemplate');
    var couponTemplate = new CouponTemplate();
    couponTemplate.id = couponTemplateId;
    // 创建user
    var user = new Parse.User();
    user.id = userId;
    // 检查用户是否已经领取了优惠券
    var query = new Parse.Query('PYCoupon');
    query.equalTo('user', user);
    query.equalTo('couponTemplate', couponTemplate);
    query.count().then(function (count) {
        if (count==0){
            var Coupon = Parse.Object.extend('PYCoupon');
            var coupon = new Coupon();
            coupon.set('couponTemplate', couponTemplate);
            coupon.set('user', user);
            coupon.save().then(function (result) {
                res.json({'code': 200, 'message': '成功领取优惠券', 'results': result});
            }, function (error) {
                res.json({'code': 400, 'message': '领取优惠券失败'});
            });
        }else {
            res.json({'code': 201, 'message': '已领取过优惠券'});
        }
    }, function (error) {
        res.json({'code': 401, 'message': '领取优惠券失败'});
    });
    //

};

//查看所有couponTemplate
exports.getCoupons = function (req, res) {
    var userId = req.query.userId;
    if (typeof userId == 'undefined'){
        res.json({'code': 200, 'message': 'userId不能为空'});
        return;
    }
    var user = new Parse.User();
    user.id = userId;
    // 查询couponTemplate
    var queryTemplate = new Parse.Query('PYCouponTemplate');
    queryTemplate.equalTo('from', 'seagou');
    // 查询user已经领取了拿些优惠券
    var query = new Parse.Query('PYCoupon');
    query.equalTo('user', user);
    query.include('couponTemplate');
    var waitFor = [queryTemplate.find(), query.find()];
    Promise.all(waitFor).then(function (results) {
        var couponTemplates = results[0];
        var coupons = results[1];
        var res_coupons = [];
        var couponsId_list = [];
        coupons.forEach(function (item) {
            // 先判断优惠券是否是seagou的优惠券
            var from = item.get('couponTemplate').get('from');
            if (typeof from != 'undefined' && from == 'seagou'){
                couponsId_list.push(item.get('couponTemplate').id);
            }
        });
        couponTemplates.forEach(function (item) {
            var temp = assert.obj2dic(item, ['channel', 'intro', 'worth', 'limitPrice']);
            temp['validityEnd'] = item.get('validityEnd').Format('yyyy-MM-dd');
            temp['validityBegin'] = item.get('validityBegin').Format('yyyy-MM-dd');
            temp['isGet'] = contains(couponsId_list, item.id);
            res_coupons.push(temp);
        });
        res.json({'code': 200, 'message': '获取coupon', 'results': res_coupons});

    }, function (error) {

    });
};

// 获取我领取的优惠券
exports.getMyCoupons = function (req, res) {
    var userId = req.query.userId;
    var sumPrice = req.query.sumPrice;
    if (typeof userId == 'undefined'){
        res.json({'code': 200, 'message': 'userId不能为空'});
        return;
    }
    var user = new Parse.User();
    user.id = userId;
    // 查询我已经领取并且没有使用的优惠券
    var query = new Parse.Query('PYCoupon');
    query.equalTo('user', user);
    query.doesNotExist('order');
    query.include('couponTemplate');
    query.find().then(function (results) {
        var response = [];
        results.forEach(function (item) {
            // 判断优惠券是否是seagou的优惠券
            var from = item.get('couponTemplate').get('from');
            if (typeof from != 'undefined' && from == 'seagou'){
                var temp = assert.obj2dic(item.get('couponTemplate'), ['channel', 'intro', 'worth', 'limitPrice']);
                var now = new Date();
                // 判断优惠券是否在可使用期间内
                if (item.get('couponTemplate').get('validityEnd')>now && item.get('couponTemplate').get('validityBegin')<now){
                    temp['validityEnd'] = item.get('couponTemplate').get('validityEnd').Format('yyyy-MM-dd');
                    temp['validityBegin'] = item.get('couponTemplate').get('validityBegin').Format('yyyy-MM-dd');
                    temp['objectId'] = item.id;
                    response.push(temp);
                }
            }
        });
        res.json({'code': 200, 'message': '获取coupon成功', 'results': response});

    }, function (error) {
        res.json({'code': 400, 'message': '获取coupon失败'});
    });
};
// 获取指定优惠券信息
exports.getCoupon = function (req, res) {
    var couponId = req.params.couponId;
    if (typeof couponId == 'undefined' || couponId == 'undefined'){
        res.json({'code': 101, 'message': 'userId,couponId不能为空'});
        return;
    }
    var query = new Parse.Query('PYCoupon');
    query.include('couponTemplate');
    query.get(couponId).then(function (coupon) {
        var temp = assert.obj2dic(coupon.get('couponTemplate'), ['channel', 'intro', 'worth', 'limitPrice']);
        temp['objectId'] = coupon.id;
        res.json({'code': 200, 'message': '获取coupon成功', 'results': temp});
    }, function (error) {
        console.log(error);
        res.json({'code': 400, 'message': '获取coupon失败'});
    });
};
exports.getOptimalCoupon = function (req, res) {
    var userId = req.body.userId;
    var sumPrice = req.body.sumPrice;
    if (assert.check_parms([userId, sumPrice])){
        res.json({'code': 101, 'message': 'userId不能为空'});
        return;
    }
    try {
        sumPrice = parseInt(sumPrice);
    }catch (error){
        res.json({'code': 102, 'message': 'sumPrice只能为数字'});
        return;
    }
    var user = new Parse.User();
    user.id = userId;
    // 查询我已经领取并且没有使用的优惠券
    var query = new Parse.Query('PYCoupon');
    query.include('couponTemplate');
    query.doesNotExist('order');
    query.equalTo('user', user);
    query.find().then(function (results) {
        var temp = {
            'worth': 0
        };
        var temps = [];
        results.forEach(function (item) {
            // 先判断获取到的优惠券是不是海外购的优惠券
            var from = item.get('couponTemplate').get('from');
            if (typeof from != 'undefined' && from == 'seagou'){
                var now = new Date();
                // 判断优惠券是否在可使用的时间范围内
                if (item.get('couponTemplate').get('validityEnd')>now && item.get('couponTemplate').get('validityBegin')<now){
                    temps.push(item);
                }
            }
        });
        // 判断可用优惠券数量是否大于0
        if (temps.length>0){
            temp = getSuitCoupon(sumPrice, temps);
        }
        res.json({'code': 200, 'message': '成功获取最优coupon', 'results': temp});
    }, function (error) {
        res.json({'code': 400, 'message': '获取最优优惠券失败'});
    });

};
// 判断对象是否在列表中
function contains(a, obj) {
    var i = a.length;
    while (i--) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}
function getSuitCoupon(sumPrice, coupons) {
    var suitCoupon = {'worth': 0};
    coupons.forEach(function (item) {
        if (sumPrice>=item.get('couponTemplate').get('limitPrice') && item.get('couponTemplate').get('worth')>suitCoupon.worth){
            suitCoupon['worth'] = item.get('couponTemplate').get('worth');
            suitCoupon['limitPrice'] = item.get('couponTemplate').get('limitPrice');
            suitCoupon['objectId'] = item.id;
        }
    });
    return suitCoupon;
}
// 获取单个商品的同步写法
exports.getXXXXX = function (req, res) {
    var productId = req.params.productId;
    var userId = req.query.userId;
    var isUserExist = typeof userId != 'undefined' && userId != '';
    if (!productId){
        res.send(assert.response_sms(400, 'productId为空'));
        return
    }
    // 创建一个user用来查询优惠券领取情况
    if (isUserExist){
        var user = new Parse.User();
        user.id = userId;
    }
    // 查询商品详情
    co(function* () {
        // 查询商品
        try {
            var product = yield new Promise(function (resolve, reject) {
                var query = new Parse.Query('OPProduct');

                    query.get(productId).then(function (result) {
                        resolve(result);
                    }, function (error) {
                        res.json({'code': 102, 'message': error.message});
                        reject(new Error(error.message));
                    });
            });
        }catch (err){
            console.log(err.message);
        }
        console.log(product);
        // 查询优惠券模板
        try {
            var templateCoupons = yield new Promise(function (resolve, reject) {
                var queryTemplateCoupon = new Parse.Query('PYCouponTemplate');
                queryTemplateCoupon.equalTo('from', 'seagou');
                queryTemplateCoupon.find().then(function (results) {
                    resolve(results);
                }, function (error) {
                    reject(new Error(error.message));
                });

            });
        }catch (err){
            console.error(err.message);
        }
        console.log(templateCoupons);
        // 如果userId存在，查询用户有哪些优惠券已经领取了
        if (isUserExist){
            var getedCoupon = yield new Promise(function (resolve, reject) {
                // 查询user已经领取的优惠券
                var queryCoupon = new Parse.Query('PYCoupon');
                queryCoupon.include('couponTemplate');
                queryCoupon.equalTo('user', user);
                queryCoupon.find(function (results) {
                    resolve(results);
                }, function (error) {
                    reject(error);
                });
            });
            console.log(getedCoupon);
        }

    }).catch(onerror);
};
// co模块error捕捉
function onerror(err) {
    // log any uncaught errors
    // co will not throw any errors you do not handle!!!
    // HANDLE ALL YOUR ERRORS!!!
    console.error(err.stack);
}